package cn.turboinfo.fuyang.api.provider.common.config

import com.fasterxml.jackson.databind.ObjectMapper
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.data.redis.connection.RedisConnectionFactory
import org.springframework.data.redis.core.RedisTemplate
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer
import org.springframework.data.redis.serializer.StringRedisSerializer

/**
 * author: sunshow.
 */
@Configuration
class CommonRedisConfig {

    @Bean
    protected fun redisTemplate(
        redisConnectionFactory: RedisConnectionFactory,
        objectMapper: ObjectMapper
    ): RedisTemplate<String, Any> {
        val redisTemplate = RedisTemplate<String, Any>()
        redisTemplate.connectionFactory = redisConnectionFactory

        // key 和 hashKey 序列化
        val keySerializer = StringRedisSerializer()
        redisTemplate.keySerializer = keySerializer
        redisTemplate.hashKeySerializer = keySerializer

        // value hashValue值的序列化
        val valueSerializer = Jackson2JsonRedisSerializer(Any::class.java)
        valueSerializer.setObjectMapper(objectMapper)
        redisTemplate.valueSerializer = valueSerializer
        redisTemplate.hashValueSerializer = valueSerializer

        redisTemplate.afterPropertiesSet()

        return redisTemplate
    }
    
}